/**
 * APMLogger 埋点
 * @author aker
 * @date 2020/3/5
 */

import * as logger from 'fluent-logger'
import * as path from 'path'
import * as fs from 'fs'

import Utils from './Utils'
import Config from './Config'

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" // Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs

export type LoggerType = 'task_end' | 'task_start'

interface ILoggerConfig {
  host: string
  sharedKey: string
}

// 用法
// APMLogger.instance.taskend()
// APMLogger.instance.taskstart()

export default class APMLogger {
  // 发送apm 埋点记录
  public async taskend() {
    const uploadParam = {
    }
    printlog("[APMLogger.taskend] uploadParam ", uploadParam)
    this.emit('task_end', uploadParam)
  }
  public async taskstart() {
    const uploadParam = {
    }
    printlog("[APMLogger.taskstart] uploadParam ", uploadParam)
    this.emit('task_start', uploadParam)
  }
  //////////////////////////////////////////
  // 准备工作
  private static logger:APMLogger
  public static registLogger() {
    this.instance
  }
  public static get instance() {
    if (!this.logger) {
      this.logger = new APMLogger
      const chromeInfo = Utils.getChromeInfo()
      const configPath = path.join(chromeInfo.homeDir, "WebImager V5.ini")
      let config:ILoggerConfig = {
        host: "apm.forensix.cn",
        sharedKey: Config.getAPMSharedKey()
      }
      if (fs.existsSync(configPath)) {
        const resConfig = Utils.parseIni(configPath) as {fluentd: any}
        if (resConfig) config = resConfig.fluentd as ILoggerConfig
      }
      logger.configure("webimager", {
        host: config.host,
        port: 24224,
        timeout: 3.0,
        reconnectInterval: 600000, // 10 minutes
        tls: true,
        security: {
          clientHostname: 'client.localdomain',
          sharedKey: config.sharedKey
        }
      })
    }
    return this.logger
  }
  public async emit(label:LoggerType, args:any) {
    return new Promise((resolve, reject) => {
      logger.emit(label, args, (err) => {
        printlog(`[AOMLogger.emit] ${label} log with err?: `, err ? err.message : "none")
        if (err) return reject(err)
        resolve()
      })
    })
  }
}
